package com.example.redis.bit.domain.init;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.RandomUtil;
import com.example.redis.bit.SpringAware;
import com.google.common.collect.Lists;
import org.redisson.api.RScript;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;

import java.util.Date;

public abstract class AbsDataInit {

    private final Logger log = LoggerFactory.getLogger(getClass());

    private RedissonClient redissonClient = SpringAware.getBean(RedissonClient.class);

    //每一次lua处理的数据大小，太长的话会引起lua超时，redis默认lua超时5秒
    protected long pageSize = Long.parseLong(SpringAware.getBean(Environment.class).getProperty("lua.pageSize"));

    //总用户的数量
    protected long totalUserCount = Long.parseLong(SpringAware.getBean(Environment.class).getProperty("demoUserCount"));;

    protected void initBitData(String luaPath, Date startDate, Date endDate){
        ClassPathResource resource = new ClassPathResource(luaPath);
        FileReader fileReader = new FileReader(resource.getFile());
        String scriptContent = fileReader.readString();

        RScript script = redissonClient.getScript();
        String SHA = script.scriptLoad(scriptContent);
        log.info("SHA:{}",SHA);

        long cnt = DateUtil.betweenDay(startDate,endDate,true);
        long pageCnt;
        for(int i=0;i<=cnt;i++){
            Date currDate = DateUtil.offsetDay(startDate,i);
            String key = DateUtil.formatDate(currDate);

            redissonClient.getKeys().delete(key);

            if(totalUserCount % pageSize == 0){
                pageCnt = totalUserCount/pageSize;
            }else{
                pageCnt = totalUserCount/pageSize + 1;
            }

            for(int j=0;j<pageCnt;j++){
                long start = j * pageSize + 1;
                long end;
                if(i == pageCnt-1){
                    end = totalUserCount;
                }else{
                    end = (j+1) * pageSize;
                }

                script.evalSha(RScript.Mode.READ_WRITE,
                        SHA,
                        RScript.ReturnType.VALUE,
                        Lists.newArrayList(),
                        key,
                        start,
                        end,
                        RandomUtil.randomInt(1000));
            }
        }
    }
}
